package com.leinao.images.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leinao.commons.Response;
import com.leinao.config.EnvironmentConfig;
import com.leinao.constant.Constant;
import com.leinao.constant.ImageErrorEnum;
import com.leinao.images.dao.FrameworkMapper;
import com.leinao.images.dao.ImagesMapper;
import com.leinao.images.dao.LanguageMapper;
import com.leinao.images.dto.*;
import com.leinao.images.service.ImagesService;
import com.leinao.util.SSHClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Collections;
import java.util.List;

/**
 * 镜像服务
 *
 * @author  suqiliang
 * @date 2019年04月18日 下午2:29:54
 *
 */
@Service
public class ImagesServiceImpl implements ImagesService {
	
	private Logger logger = LoggerFactory.getLogger(ImagesServiceImpl.class);
	
	@Autowired
	private ImagesMapper imagesMapper;

	@Autowired
	private LanguageMapper languageMapper;

	@Autowired
	private FrameworkMapper frameworkMapper;

	@Autowired
	EnvironmentConfig envConfig;

	@Autowired
	private SSHClient sshClient;

	/**
	 * @Description 根据编程语言和框架匹配镜像列表
	 * @param language : 编程语言
	 * @param framework : 框架
	 * @param userId : 用户Id
	 * @author lizi
	 * @date 2019/04/18 上午11:49
	 */
	@Override
	public Response<List<ImagesDto>> getImagesList(String language, String framework, String userId) {
		List<ImagesDto> imagesList = imagesMapper.getImagesList(language, framework, userId);
		if(CollectionUtils.isEmpty(imagesList)) {
			return Response.ok(Collections.emptyList());
		} else {
			logger.info(String.format("imagesList size %s", imagesList.size()));
			return Response.ok(imagesList);
		}
	}

	/**
	 * @Description 获取编程语言列表
	 * @author lizi
	 * @date 2019/04/18 上午11:49
	 */
	@Override
	public Response<List<LanguageDto>> getLanguageList() {
		List<LanguageDto> languageList = languageMapper.getLanguageList();
		if(CollectionUtils.isEmpty(languageList)) {
			return Response.ok(Collections.emptyList());
		} else {
			logger.info(String.format("languageList size %s", languageList.size()));
			return Response.ok(languageList);
		}
	}

	/**
	 * @Description 获取框架列表
	 * @author lizi
	 * @date 2019/04/18 上午11:49
	 */
	@Override
	public Response<List<FrameworkDto>> getFrameworkList() {
		List<FrameworkDto> frameworkList = frameworkMapper.getFrameworkList();
		if(CollectionUtils.isEmpty(frameworkList)) {
			return Response.ok(Collections.emptyList());
		} else {
			logger.info(String.format("frameworkList size %s", frameworkList.size()));
			return Response.ok(frameworkList);
		}
	}

	/**
	 *
	 * @Description: 创建自定义镜像
	 * @param name : 名称
	 * @param type : 类型: 1-默认提供，2-推荐提供，3-用户自定义
	 * @param userId : 用户Id
	 * @param content : 镜像简介
	 * @param contentMk : 镜像mk简介
	 * @param languageId : 算法ID
	 * @param frameworkId : 框架ID
	 * @param file : 上传文件
	 * @return: com.leinao.commons.Response<java.lang.Void>
	 * @Author: 曹阳
	 * @date: 2019/5/15 11:33
	 *
	 **/
	@Override
	public Response<Void> createUserImage(MultipartFile file, String name, Integer type, String userId, String content, String contentMk, Long languageId, Long frameworkId) {
		Integer count = imagesMapper.getUserImageCount(userId);
		StringBuffer fileContent = new StringBuffer();
		if(count < 3) {
			String filePath = envConfig.getDockerfilePath() + userId + "/" + name + "/Dockerfile";
			File dest = new File(filePath);
			File fileParent = dest.getParentFile();
			if (!fileParent.exists()) {
				fileParent.mkdirs();
			}else{
				dest.delete();
			}
			try {
				file.transferTo(dest);
				BufferedReader br=null;
					br=new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "utf-8"));
					String temp;
					while((temp=br.readLine())!=null){
						fileContent.append(temp).append("\n");
					}
						br.close();
			} catch (Exception e) {
				e.printStackTrace();
				fileParent.delete();
				return Response.error(Constant.RESPONSE_STATUS_SUCCESS, ImageErrorEnum.IMAGE_NAME_EXIST.getSeq(), ImageErrorEnum.IMAGE_NAME_EXIST.getDesc());
			}
			ImagesDto imagesDto = new ImagesDto();
			imagesDto.setName(name);
			imagesDto.setContent(content);
			imagesDto.setContentMk(contentMk);
			imagesDto.setType(type);
			imagesDto.setUserId(userId);
			String path = envConfig.getImagesPath() + name;
			Long time = System.currentTimeMillis();
			imagesDto.setPath(path);
			imagesDto.setDomain(envConfig.getImagesDomain());
			imagesDto.setCreateTime(time);
			imagesDto.setUpdateTime(time);
			String fileContentRE = fileContent.toString().replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "*");
			imagesDto.setFileContent(fileContentRE);
			int result = imagesMapper.createUserImage(imagesDto);
			if (result == 1) {
				ImagesRelationDto imagesRelationDto = new ImagesRelationDto();
				imagesRelationDto.setImageId(imagesDto.getId());
				imagesRelationDto.setLanguageId(languageId);
				imagesRelationDto.setFrameworkId(frameworkId);
				imagesRelationDto.setUpdateTime(time);
				imagesRelationDto.setCreateTime(time);
				imagesMapper.createImagesRelation(imagesRelationDto);
				return Response.ok();
			} else {
				return Response.error(Constant.RESPONSE_STATUS_SUCCESS, ImageErrorEnum.IMAGE_NAME_EXIST.getSeq(), ImageErrorEnum.IMAGE_NAME_EXIST.getDesc());
			}
		}else{
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, ImageErrorEnum.IMAGE_Limit.getSeq(), ImageErrorEnum.IMAGE_Limit.getDesc());
		}
	}

	/**
	 *
	 * @Description: 通过用户ID查询用户自定义镜像
	 * @param userId : 用户ID
	 * @param pageNum : 当前页
	 * @param pageSize : 每页条数
	 * @return: com.leinao.commons.Response<java.util.List<com.leinao.images.dto.ImagesDto>>
	 * @Author: 曹阳
	 * @date: 2019/5/15 16:27
	 *
	 **/
	@Override
	public Response<PageInfo> getUserImagesList(String userId, Integer pageNum, Integer pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		List<ImageInfo> userImagesList = imagesMapper.getUserImagesList(userId);
        PageInfo pageInfo = new PageInfo(userImagesList);
		return Response.ok(pageInfo);
	}

	/**
	 *
	 * @Description: 通过镜像ID查询用户自定义镜像
	 * @param id : 镜像ID
	 * @return: com.leinao.commons.Response<java.util.List<com.leinao.images.dto.ImagesDto>>
	 * @Author: 曹阳
	 * @date: 2019/5/15 16:27
	 *
	 **/
	@Override
	public Response<ImageInfo> getUserImageById(Long id, String userId) {
		ImageInfo imageInfo = imagesMapper.getUserImageById(id, userId);
		if(imageInfo != null) {
			return Response.ok(imageInfo);
		}else{
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, ImageErrorEnum.IMAGE_IS_NOT_CREATED.getSeq(), ImageErrorEnum.IMAGE_IS_NOT_CREATED.getDesc(), null);
		}
	}

	/**
	 *
	 * @Description:  更新镜像简介
	 * @param id : 镜像ID
	 * @param content : 镜像简介
	 * @param contentMk : 镜像mk简介
	 * @param userId : 用户ID
	 * @return: com.leinao.commons.Response<java.lang.Void>
	 * @Author: 曹阳
	 * @date: 2019/5/15 17:30
	 *
	 **/
	@Override
	public Response<Void> updateUserImageContent(Long id, String content, String contentMk, String userId) {
		ImagesDto imagesDto = new ImagesDto();
		imagesDto.setId(id);
		imagesDto.setContent(content);
		imagesDto.setContentMk(contentMk);
		imagesDto.setUserId(userId);
		Long time = System.currentTimeMillis();
		imagesDto.setUpdateTime(time);
		int result = imagesMapper.updateUserImage(imagesDto);
		if(result == 1) {
			return Response.ok();
		}else{
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, ImageErrorEnum.IMAGE_IS_NOT_CREATED.getSeq(), ImageErrorEnum.IMAGE_IS_NOT_CREATED.getDesc());
		}
	}

	/**
	 *
	 * @Description: 删除镜像
	 * @param id : 镜像ID
     * @param userId : 用户ID
	 * @return: com.leinao.commons.Response<java.lang.Void>
	 * @Author: 曹阳
	 * @date: 2019/5/17 10:08
	 *
	 **/
	@Override
	public Response<Void> deleteUserImage(Long id, String userId) {
		ImageInfo imageInfo = imagesMapper.getUserImageById(id, userId);
		if(imageInfo == null){
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, ImageErrorEnum.IMAGE_IS_NOT_CREATED.getSeq(), ImageErrorEnum.IMAGE_IS_NOT_CREATED.getDesc());
		}
		String filePath = envConfig.getDockerfilePath() + userId + "/" + imageInfo.getName() + "/Dockerfile";
		File dest = new File(filePath);
		dest.delete();
		File fileParent = dest.getParentFile();
		fileParent.delete();
		int result = imagesMapper.deleteUserImage(id, userId);
		if(result == 1) {
			return Response.ok();
		}else{
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, ImageErrorEnum.IMAGE_IS_NOT_CREATED.getSeq(), ImageErrorEnum.IMAGE_IS_NOT_CREATED.getDesc());
		}
	}
}
